package com.xinghai.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.domain.*;
import com.xinghai.mapper.JkqBadgeMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.mapper.JkqUserBadgeMapper;
import com.xinghai.service.IJkqUserBadgeService;

import javax.annotation.Resource;

/**
 * 用户徽章Service业务层处理
 *
 * @author xinghai
 * @date 2025-08-02
 */
@Service
public class JkqUserBadgeServiceImpl extends MPJBaseServiceImpl<JkqUserBadgeMapper, JkqUserBadge>
        implements IJkqUserBadgeService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private JkqBadgeMapper jkqBadgeMapper;
    /**
     * 查询用户徽章列表
     *
     * @param jkqUserBadge 用户徽章
     * @return 用户徽章集合
     */
    @Override
    public List<JkqUserBadge> list(JkqUserBadge jkqUserBadge) {
        MPJLambdaWrapper<JkqUserBadge> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(JkqUserBadge.class)
                .setAlias("ub")
                .selectAs(JkqBadge::getName,JkqUserBadge::getBadgeName)
                .selectAs(JkqBadge::getImageUrl,JkqUserBadge::getBadgeImage)
                .selectAs(JkqUser::getNickname,JkqUserBadge::getUserName)
                .selectAs(JkqUser::getImageUrl,JkqUserBadge::getUserImage)
                .selectAs(JkqUser::getHealthUserId,JkqUserBadge::getHealthUserId)
                .selectAs(JkqUserCopy::getNickname,JkqUserBadge::getHealthUserName)
                .leftJoin(JkqUser.class, "u", JkqUser::getId, JkqUserBadge::getUserId)
                .leftJoin(JkqUserCopy.class,"u2",JkqUserCopy::getId,JkqUser::getHealthUserId)
                .leftJoin(JkqBadge.class, "b", JkqBadge::getId, JkqUserBadge::getBadgeId);
        if (jkqUserBadge.getBadgeId()!= null ){
            queryWrapper.eq("ub.badge_id", jkqUserBadge.getBadgeId());
        }
        if (jkqUserBadge.getUserId()!= null ){
            queryWrapper.eq("ub.user_id", jkqUserBadge.getUserId());
        }
        if (jkqUserBadge.getUserName()!= null && !jkqUserBadge.getUserName().isEmpty()){
            queryWrapper.like("u.nickname", jkqUserBadge.getUserName());
        }
        if (jkqUserBadge.getUserName()!= null && !jkqUserBadge.getUserName().isEmpty()){
            queryWrapper.like("u.health_user_id", jkqUserBadge.getUserName());
        }
        if (jkqUserBadge.getStatus()!= null  && !jkqUserBadge.getStatus().isEmpty()){
            queryWrapper.eq("ub.status", jkqUserBadge.getStatus());
        }
        if (jkqUserBadge.getParams().get("beginCreateTime")!= null && !"".equals(jkqUserBadge.getParams().get("beginCreateTime"))
                &&jkqUserBadge.getParams().get("endCreateTime")!= null && !"".equals(jkqUserBadge.getParams().get("endCreateTime"))){
            queryWrapper.between("ub.create_time", jkqUserBadge.getParams().get("beginCreateTime"),jkqUserBadge.getParams().get("endCreateTime"));
        }
        return this.baseMapper.selectJoinList(JkqUserBadge.class,queryWrapper);
    }

    /**
     * 导入用户徽章信息
     *
     * @param list 用户徽章信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<JkqUserBadge> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            JkqUserBadgeMapper jkqUserBadgeMapper = sqlSession.getMapper(JkqUserBadgeMapper.class);
            list.forEach(jkqUserBadgeMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public List<JkqBadge> getByUserId(Long loginId,Integer pageSize) {
        //创建联表查询，用过user_id关联 jkq_user_badge和jkq_badge
        QueryWrapper<JkqUserBadge> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginId);
        List<JkqUserBadge> list = this.list(queryWrapper);
        List<Long> badgeIds = list.stream().map(JkqUserBadge::getBadgeId).collect(Collectors.toList());
        if (!badgeIds.isEmpty()) {
            PageUtils.orderBy("create_time desc");
            if (pageSize == null){
                pageSize = 4;
            }
            PageUtils.startPage(1,pageSize);
            return jkqBadgeMapper.selectBatchIds(badgeIds);
        }
        return new ArrayList<>();
    }

    @Override
    @Transactional
    public void getBadgePower(BadgeItem badgeItem) {
        Long count = baseMapper.selectCount(new QueryWrapper<JkqUserBadge>()
                .eq("badge_id", badgeItem.getBadgeId())
                .eq("user_id", badgeItem.getUserId()));
        if (count == 0){
            JkqUserBadge jkqUserBadge = new JkqUserBadge();
            jkqUserBadge.setBadgeId(badgeItem.getBadgeId());
            jkqUserBadge.setUserId(badgeItem.getUserId());
            jkqUserBadge.setCreateTime(DateUtils.getNowDate());
            baseMapper.insert(jkqUserBadge);
        }
    }
}
